//
//  PKRadioMainViewController.m
//  AMomentApp
//
//  Created by lanou on 15/9/25.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "PKRadioMainViewController.h"
#import "PKRequestManager.h"
#import "PKRadioMainListCell.h"
#import "PKRadioMovieModel.h"
#import "PKShufflingPictureView.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
#import "LORefresh.h"
#import "MJRefresh.h"
#import "PKRadioMainDetailController.h"
#import "Reachability.h"
@interface PKRadioMainViewController () <UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) PKShufflingPictureView *shufflView;
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) NSMutableArray *mainArray;
@property (nonatomic, strong) NSMutableArray *movieArray;
@property (nonatomic, strong) NSMutableArray *picArray;
@property (nonatomic, strong) UITableView *radioTabView;
@property (nonatomic, assign) int start;
@property (nonatomic, strong) Reachability *reach;
@end

@implementation PKRadioMainViewController

-(NSMutableArray *)mainArray
{
    if (_mainArray == nil) {
        self.mainArray = [NSMutableArray array];
    }
    return _mainArray;
}

-(NSMutableArray *)movieArray
{
    if (_movieArray == nil) {
        self.movieArray = [NSMutableArray array];
    }
    return _movieArray;
}

-(NSMutableArray *)picArray
{
    if (_picArray == nil) {
        self.picArray = [NSMutableArray array];
    }
    return _picArray;
}

- (void)configureData
{
    NSMutableDictionary *pardic = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%d",self.start],@"start",@"1",@"client",@"63A94D37-33F9-40FF-9EBB-481182338873",@"deviceid",@"",@"auth",@"3.0.2",@"version",@"9",@"limit", nil];
    
    if (self.start >= 9) {
        [PKRequestManager PKRequestManagerrequsetWithType:POST URLString:@"http://api2.pianke.me/ting/radio_list" ParDIc:pardic finish:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            for (NSDictionary *listDic in dic[@"data"][@"list"]) {
                PKRadioMainListModel *radioModel = [[PKRadioMainListModel alloc]init];
                [radioModel setValuesForKeysWithDictionary:listDic];
                radioModel.uname = listDic[@"userinfo"][@"uname"];
                [self.mainArray addObject:radioModel];
                [self.radioTabView.footer endRefreshing];
                [_radioTabView reloadData];
            }
        } error:^(NSError *error) {
            NSLog(@"error:%@",[error localizedDescription]);
        }];
    }else
    {
        [PKRequestManager PKRequestManagerrequsetWithType:POST URLString:@"http://api2.pianke.me/ting/radio" ParDIc:pardic finish:^(NSData *data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
            for (NSDictionary *radioDic in dic[@"data"][@"alllist"]) {
                PKRadioMainListModel *radioModel = [[PKRadioMainListModel alloc]init];
                [radioModel setValuesForKeysWithDictionary:radioDic];
                radioModel.uname = radioDic[@"userinfo"][@"uname"];
                [self.mainArray addObject:radioModel];
            }
            
            for (NSDictionary *radioDic in dic[@"data"][@"carousel"]) {
                PKRadioMovieModel *radioModel = [[PKRadioMovieModel alloc]init];
                [radioModel setValuesForKeysWithDictionary:radioDic];
                [self.movieArray addObject:radioModel];
            }
            
            for (NSDictionary *radioDic in dic[@"data"][@"hotlist"]) {
                PKRadioMainListModel *radioModel = [[PKRadioMainListModel alloc]init];
                [radioModel setValuesForKeysWithDictionary:radioDic];
                radioModel.uname = radioDic[@"userinfo"][@"uname"];
                [self.picArray addObject:radioModel];
            }
            [self showPictureInTableHeardVIew];
            
            // 结束刷新（如果是gif图 用gifHeader）
            [_radioTabView.gifHeader endRefreshing];
            
            [self.radioTabView.footer endRefreshing];
            [_radioTabView reloadData];
        } error:^(NSError *error) {
            NSLog(@"%@",[error localizedDescription]);
        }];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.titleLable.text = @"电台";
    [self.leftButton addTarget:self action:@selector(getBackRootViewController:) forControlEvents:UIControlEventTouchUpInside];
    _start = 0;
    [self configureData];
    
    _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 70, SCREEN_WIDTH, SCREEN_WIDTH-70)];
    
    _radioTabView = [[UITableView alloc]initWithFrame:CGRectMake(0, 70, SCREEN_WIDTH, SCREEN_HEIGHT-70) style:UITableViewStylePlain];
    _radioTabView.delegate = self;
    _radioTabView.dataSource = self;
    _radioTabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _radioTabView.tableHeaderView = self.headerView;
    [_radioTabView registerClass:[PKRadioMainListCell class] forCellReuseIdentifier:@"radio"];
    [self.view addSubview:_radioTabView];
    
    // 刷新数据
    __weak PKRadioMainViewController *radioMainVC = self;
    /*
    [_radioTabView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        [radioMainVC configureData];
    }];
     */
    
    [_radioTabView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderGif refreshingBlock:^{
        radioMainVC.start += 9;
        [radioMainVC configureData];
    }];
    LORefresh *view = _radioTabView.gifHeader;
    [view setGifName:@"demo"];
    
    
    self.radioTabView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        radioMainVC.start += 9;
        [self configureData];
    }];
    ///开启网络状况的监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    self.reach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    [self.reach startNotifier]; //开始监听，会启动一个run loop
    [NSTimer scheduledTimerWithTimeInterval:6 target:self selector:@selector(shufflPicture) userInfo:nil repeats:YES];
    // Do any additional setup after loading the view.
}

//通知
-(void)reachabilityChanged:(NSNotification*)note
{
    Reachability * reach = [note object];
    NSParameterAssert([reach isKindOfClass: [Reachability class]]);
    NetworkStatus status = [reach currentReachabilityStatus];
    
    //    //用于检测是否是WIFI
    //    NSLog(@"%d",([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable));
    //    //用于检查是否是3G
    //    NSLog(@"%d",([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable));
    
    if (status == NotReachable) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"当前网络不可用,请检查您的网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
        NSLog(@"Notification Says Unreachable");
    }else if(status == ReachableViaWWAN){
        
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"您已连接移动网络,请考虑连接Wifi" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertView show];
    }else if(status == ReachableViaWiFi){
        
        //        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"您已连接WIfi网络,请放心使用" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        //        [alertView show];
        NSLog(@"连接上wifi");
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}



// ******************** 轮播图界面 *************************
- (void)showPictureInTableHeardVIew
{
    _shufflView = [[PKShufflingPictureView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
    _shufflView.scrollView.delegate = self;
    [self.movieArray addObject:_movieArray[0]];
    for (int i = 0; i < 4; i++) {
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH*i, 0, SCREEN_WIDTH, SCREEN_WIDTH-200)];
        imageView.userInteractionEnabled = YES;
        PKRadioMovieModel *radioModel = self.movieArray[i];
        [imageView sd_setImageWithURL:[NSURL URLWithString:radioModel.img]];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(enterMovieDetailControl:)];
        [imageView addGestureRecognizer:tap];
        [self.shufflView.scrollView addSubview:imageView];
    }
    for (int i = 0; i < 3; i++) {
        PKRadioMainListModel *picModel = self.picArray[i];
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(10 + SCREEN_WIDTH/3*i, SCREEN_WIDTH-190, SCREEN_WIDTH/3-15, SCREEN_WIDTH/3-15);
        button.tag = 100 + i;
        [button addTarget:self action:@selector(enterRadioDetailControl:) forControlEvents:UIControlEventTouchUpInside];
        [button sd_setImageWithURL:[NSURL URLWithString:picModel.coverimg] forState:UIControlStateNormal];
        [self.shufflView addSubview:button];
    }
    [self.headerView addSubview:_shufflView];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ((_shufflView.scrollView.contentOffset.x + SCREEN_WIDTH) > _shufflView.scrollView.contentSize.width) {
        _shufflView.scrollView.contentOffset = CGPointMake(0, 0);
    }
    if (_shufflView.scrollView.contentOffset.x < 0) {
        _shufflView.scrollView.contentOffset = CGPointMake(SCREEN_WIDTH *3, 0);
    }
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _shufflView.pageControl.currentPage = _shufflView.scrollView.contentOffset.x / SCREEN_WIDTH;
    if (_shufflView.scrollView.contentOffset.x == SCREEN_WIDTH * 3) {
        _shufflView.pageControl.currentPage = 0;
    }
}

- (void)shufflPicture
{
    if (_shufflView.pageControl.currentPage < 2) {
        _shufflView.pageControl.currentPage++;
    }else
    {
        _shufflView.pageControl.currentPage = 0;
    }
    _shufflView.scrollView.contentOffset = CGPointMake(_shufflView.pageControl.currentPage*SCREEN_WIDTH, 0);
}


- (void)enterMovieDetailControl:(UITapGestureRecognizer *)tap
{
    NSLog(@"hehe");
}

- (void)enterRadioDetailControl:(UIButton *)button
{
    PKRadioMainDetailController *radioMainDVC = [[PKRadioMainDetailController alloc]init];
    
    radioMainDVC.radioId = ((PKRadioMainListModel *)self.picArray[button.tag - 100]).radioid;
    radioMainDVC.string = ((PKRadioMainListModel *)self.picArray[button.tag - 100]).title;
    [self.navigationController pushViewController:radioMainDVC animated:YES];
}


// ********************* 电台列表界面 *******************
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [PKRadioMainListCell heightForRadioCell];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.mainArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    PKRadioMainListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"radio" forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellAccessoryNone;
    cell.configureModel = self.mainArray[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    PKRadioMainListModel *radioModel = self.mainArray[indexPath.row];
    PKRadioMainDetailController *radioDC = [[PKRadioMainDetailController alloc]init];
    radioDC.string = radioModel.title;
    radioDC.radioId = radioModel.radioid;
    [self.navigationController pushViewController:radioDC animated:YES];
}

// 返回主分类界面(RootViewController)
- (void)getBackRootViewController:(UIButton *)button
{
    [UIView animateWithDuration:0.5 animations:^{
        self.view.center = CGPointMake(SCREEN_WIDTH/2*3, SCREEN_HEIGHT/2);
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
